package ru.mcfr.oxygen.framework.operations;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import ro.sync.ecss.extensions.api.*;
import ro.sync.ecss.extensions.api.node.AuthorDocumentFragment;
import ro.sync.ecss.extensions.api.node.AuthorNode;

import javax.swing.text.BadLocationException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: ws
 * Date: 4/18/11
 * Time: 4:33 PM
 * To change this template use File | Settings | File Templates.
 */
public class DeleteAllIdOperation implements AuthorOperation{

    private AuthorDocumentController controller = null;

    private void RemoveAllID(Element element){
        if (element.getNodeType() == Node.ELEMENT_NODE){
            element.removeAttribute("id");
            NodeList childs = element.getChildNodes();
            for (int i = 0; i < childs.getLength(); i++){
                if (childs.item(i).getNodeType() == Node.ELEMENT_NODE)
                    RemoveAllID((Element) childs.item(i));
            }
        }
    }

    public void doOperation(AuthorAccess authorAccess, ArgumentsMap argumentsMap) throws IllegalArgumentException, AuthorOperationException {
        controller = authorAccess.getDocumentController();
        ArrayList<String> lostElements = new ArrayList<String>();
        lostElements.add("метаданные");
        lostElements.add("редакции");
        lostElements.add("ссылки");

        List<AuthorNode> nodes = controller.getAuthorDocumentNode().getContentNodes();
        for (AuthorNode node : nodes){
            if (!lostElements.contains(node.getName())){

                AuthorDocumentFragment fragment = null;
                try {
                    fragment = controller.createDocumentFragment(node, true);
                    String xmlFragment = controller.serializeFragmentToXML(fragment);
                    Document XMLDoc = null;
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    try {
                        DocumentBuilder db = dbf.newDocumentBuilder();
                        XMLDoc = db.parse(new ByteArrayInputStream(xmlFragment.getBytes("UTF-8")));

                        RemoveAllID(XMLDoc.getDocumentElement());

                        OutputFormat opfrmt = new OutputFormat(XMLDoc, "UTF-8", false);
                        opfrmt.setPreserveSpace(false);
                        opfrmt.setOmitDocumentType(true);
                        opfrmt.setOmitXMLDeclaration(true);
                        StringWriter stringOut = new StringWriter();
                        XMLSerializer serial = new XMLSerializer(stringOut, opfrmt);
                        try {
                            serial.asDOMSerializer();
                            serial.serialize(XMLDoc);
                            String xmlString = stringOut.toString();
                            authorAccess.getWorkspaceAccess().showErrorMessage(xmlString);

                            int pos = node.getStartOffset();

                            if (!xmlString.isEmpty()) {

                                try {

                                    controller.beginCompoundEdit();

                                    controller.deleteNode(node);

                                    controller.insertXMLFragment(xmlString, pos);

                                } finally {

                                    controller.endCompoundEdit();

                                }
                            }
                        } catch (java.io.IOException ioe) {
                            authorAccess.getWorkspaceAccess().showErrorMessage(ioe.getLocalizedMessage());
                        }

                    } catch (Exception e) {
                        authorAccess.getWorkspaceAccess().showErrorMessage(e.getLocalizedMessage());
                    }
                } catch (BadLocationException e) {
                    authorAccess.getWorkspaceAccess().showErrorMessage(e.getLocalizedMessage());
                }


            }
        }

    }

    public ArgumentDescriptor[] getArguments() {
        return new ArgumentDescriptor[0];  //To change body of implemented methods use File | Settings | File Templates.
    }

    public String getDescription() {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }
}
